#pragma once
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
namespace Server
{
    static const std::string defaultIp = "0.0.0.0";
    static const int gnum = 1024;
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR
    };
    typedef std::function<void(int, std::string, uint16_t, std::string)> func_t;
    class UdpServer
    {
    public:
        UdpServer(const func_t &cb, const uint16_t &port, const std::string &ip = defaultIp)
            : _callback(cb), _port(port), _ip(ip), _sockfd(-1)
        {
        }
        void initServer()
        {
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                std::cerr << "socket error: " << errno << " : " << strerror(errno) << std::endl;
                exit(SOCKET_ERR);
            }
            std::cout << "socket success : " << _sockfd << std::endl;
            struct sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = htonl(INADDR_ANY);
            int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n == -1)
            {
                std::cerr << "bind error : " << errno << " : " << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }
        }
        void start()
        {
            char buffer[gnum];
            for (;;)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
                if (s > 0)
                {
                    buffer[s] = 0;
                    std::string clientip = inet_ntoa(peer.sin_addr);
                    uint16_t clientport = ntohs(peer.sin_port);
                    std::string message = buffer;
                    std::cout << clientip << "[" << clientport << "]# " << message << std::endl;
                    _callback(_sockfd,clientip,clientport,message);
                }
            }
        }
        ~UdpServer()
        {
        }

    private:
        int _sockfd;
        std::string _ip;
        uint16_t _port;
        func_t _callback;
    };
}